//
//  EditViewController.m
//  Address-book
//
//  Created by 任伟 on 16/1/3.
//  Copyright © 2016年 任伟. All rights reserved.
//

#import "EditViewController.h"

@interface EditViewController ()
@property (weak, nonatomic) IBOutlet UITextField* nameField;
@property (weak, nonatomic) IBOutlet UITextField* numberField;
@property (weak, nonatomic) IBOutlet UIButton* saveButton;
@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 赋初始值
    self.nameField.text = self.contact.name;
    self.numberField.text = self.contact.number;
    
    //添加保存按钮的监听
    [self.saveButton addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];}

- (IBAction)editClick:(UIBarButtonItem*)sender {

    if (self.saveButton.hidden) {
        
        sender.title = @"取消";
        self.nameField.enabled = YES;
        self.numberField.enabled = YES;
        self.saveButton.hidden = NO;
        
        [self.numberField becomeFirstResponder];
    
    } else {
        
        sender.title = @"编辑";
        self.nameField.enabled = NO;
        self.numberField.enabled = NO;
        self.saveButton.hidden = YES;
        
        // 取消的时候使用之前的数据
        self.nameField.text = self.contact.name;
        self.numberField.text = self.contact.number;
    }
    
}

// 保存按钮的点击事件
- (void)save
{
    
    self.contact.name = self.nameField.text;
    self.contact.number = self.numberField.text;
    
    // 判断
    if ([self.delegate respondsToSelector:@selector(editViewController:withContact:)]) {
        
        ContactModel* con = [[ContactModel alloc] init];
        con.name = self.nameField.text;
        con.number = self.numberField.text;
        
        // 执行
        [self.delegate editViewController:self withContact:con];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
